﻿Imports Futuros.BL
Imports Futuros.model
Imports Futuros.DAO
Imports System.Windows.Forms.ErrorProvider

Public Class frmRegistarCostos
    Dim strCustid As String
    Dim strOrigen As String
    Dim strPuerto As String
    Dim strProducto As String
    Dim objCbotProd As xm_cbot_prod
    Dim objCbotMes As xm_cbot_mes
    Dim objsegdeg As segdef
    Dim intCantNot As Integer
    Dim bModoBusqueda As Boolean
    'Dim strMotonave As String
    Dim intCantPuntos As Integer
    Dim ErrorProvider1 As System.Windows.Forms.ErrorProvider
    Private Sub actualizarCalculoCostos(ByVal lsDet As List(Of xm_cierre_det))
        If cmbEstado.SelectedIndex = 0 Then
            Dim y As Integer = 0
            For Each r As DataGridViewRow In dgvDetCost.Rows
                r.Cells(2).Value = lsDet(y).Total_cost
                y += 1
            Next
        End If
    End Sub
    Private Sub actualizarCalculos()
        If cmbEstado.SelectedIndex = 0 Then
            txtCantidadContratos.Text = BLCostos.calcularContratos(txtQtyCierre.Text, objCbotProd.Fact_contrato).ToString("f2")
            txtSpread.Text = BLCostos.calcularSpread(txtPrecVenta.Text, obtenerCostoEnGrillaById("TALM")).ToString("f2")
            txtCompensacion.Text = BLCostos.calcularCompensacion(txtFutCompra.Text, obtenerCostoEnGrillaById("FUT"), txtQtyCierre.Text).ToString("f2")
            txtTotal.Text = obtenerCostoEnGrillaById("TALM").ToString("f2")
        End If
    End Sub
    Private Sub actualizarCostos()
        If cmbEstado.SelectedIndex = 0 Then
            If txtOpNbr.Text <> "" Then
                Me.Cursor = Cursors.WaitCursor
                BL.BLCostos.guardarCostos(txtOpNbr.Text, strCustid, txtProducto.Text, dtpFecha.Value.Date.ToString("s"), _
                                          strOrigen, strPuerto, txtCostoFinanc.Text, TryCast(cmbMotonave.SelectedItem, segdef).Id, txtQtyCierre.Text, _
                                          txtUM.Text, txtPrecVenta.Text, CType(cmbCbotFut.SelectedItem, xm_cbot_mes).Id_cbot, _
                                          CType(cmbCbotPrim.SelectedItem, xm_cbot_mes).Id_cbot, txtPerpost.Text, txtHolgSeg.Text, _
                                          txtTasaSeg.Text, txtPlazoVenta.Text, txtOverhead.Text, txtCantidadContratos.Text, _
                                          txtSpread.Text, txtMerma.Text, cmbTipoVenta.SelectedItem.ToString, _
                                          CType(cmbTipoDespacho.SelectedItem, tipodespacho).ShipViaId, txtFutCompra.Text, _
                                          IIf(cmbEstado.SelectedIndex = 0, "A", "C"), CType(cmbTipoPresent.SelectedItem, segdef).Id, _
                                          obtenerDetallesCostos())
                Me.Cursor = Cursors.Arrow
            End If
        End If
    End Sub
    Private Sub actualizarCBOT()
        cargarCBot()
    End Sub
    Private Sub actualizarUm()
        txtUM.Text = BLCostos.obtenerUmByClassId(txtProducto.Text)
    End Sub
    Private Sub cargarCabecera()
        Dim objxm_cierre_enc As xm_cierre_enc = BLCostos.cargarCostoEnc(txtOpNbr.Text)
        If objxm_cierre_enc.Cierre_op <> "" Then
            'Cargar Datos generales
            txtCliente.Text = BLCostos.obtenerNombreCliente(objxm_cierre_enc.Custid)
            strCustid = objxm_cierre_enc.Custid
            txtProducto.Text = objxm_cierre_enc.Classid
            objCbotProd = BLCostos.obtenerCbotProducto(txtProducto.Text)
            dtpFecha.Value = objxm_cierre_enc.Fecha_op
            txtOrigen.Text = BLCostos.obtenerNombreOrigen(objxm_cierre_enc.Origen)
            strOrigen = objxm_cierre_enc.Origen
            txtPuerto.Text = BLCostos.obtenerNombrePuerto(objxm_cierre_enc.Pto_destino)
            strPuerto = objxm_cierre_enc.Pto_destino
            txtCostoFinanc.Text = objxm_cierre_enc.Tasa_Interes.ToString("F2")
            'objsegdeg = BLCostos.obtenerMotonaveById(objxm_cierre_enc.Motonave)
            cmbMotonave.SelectedIndex = obtenerIndiceNave(cmbMotonave, objxm_cierre_enc.Motonave)
            txtCantidadContratos.Text = objxm_cierre_enc.Cant_contratos
            txtUM.Text = objxm_cierre_enc.Um_cierre
            txtQtyCierre.Text = objxm_cierre_enc.Qty_cierre.ToString("F2")
            txtPrecVenta.Text = objxm_cierre_enc.Precio_venta.ToString("F2")

            cmbTipoVenta.SelectedIndex = cmbTipoVenta.FindString(objxm_cierre_enc.Tip_venta.Trim)
            cmbTipoDespacho.SelectedIndex = obtenerIndiceDespacho(cmbTipoDespacho, objxm_cierre_enc.Tip_despacho)
            cmbTipoPresent.SelectedIndex = obtenerIndiceNave(cmbTipoPresent, objxm_cierre_enc.Tip_presen)
            txtSpread.Text = objxm_cierre_enc.Monto_spread.ToString("F2")
            txtFutCompra.Text = objxm_cierre_enc.Futuro_compra.ToString("F2")

            If objxm_cierre_enc.Estado = "A" Then
                cmbEstado.SelectedIndex = 0
            Else
                cmbEstado.SelectedIndex = 1
            End If
            'IIf(objxm_cierre_enc.Estado.Trim = "I", cmbEstado.SelectedIndex = 0, cmbEstado.SelectedIndex = 1)
            cargarCBot()
            cmbCbotFut.SelectedIndex = obtenerIndiceCbot(cmbCbotFut, objxm_cierre_enc.Id_cbot_futuro)
            cmbCbotPrim.SelectedIndex = obtenerIndiceCbot(cmbCbotPrim, objxm_cierre_enc.Id_cbot_prima)

        End If
    End Sub
    Private Sub cargarCBot()
        cmbCbotFut.Items.Clear()
        cmbCbotPrim.Items.Clear()
        For Each obj As xm_cbot_mes In BLCostos.obtenerCbotMes(objCbotProd.Id_prod)
            cmbCbotFut.Items.Add(obj)
            cmbCbotPrim.Items.Add(obj)
        Next
        'cmbCbotFut.AutoCompleteCustomSource.Clear()
        'cmbCbotFut.AutoCompleteCustomSource = MySource
        'cmbCbotPrim.AutoCompleteCustomSource.Clear()
        'cmbCbotPrim.AutoCompleteCustomSource = MySource
    End Sub
    Private Sub cargarCierres()
        Dim MySource As New AutoCompleteStringCollection()

        MySource.AddRange(BLCostos.obtenerCierres.ToArray)
        txtOpNbr.AutoCompleteCustomSource.Clear()
        txtOpNbr.AutoCompleteCustomSource = MySource
    End Sub
    Private Sub cargarClientes()
        Dim MySource As New AutoCompleteStringCollection()

        MySource.AddRange(BLCostos.obtenerClientes.ToArray)
        txtCliente.AutoCompleteCustomSource.Clear()
        txtCliente.AutoCompleteCustomSource = MySource
    End Sub
    Private Sub cargarDetalles()
        Dim lsCostos As List(Of xm_cost_item) = BLCostos.cargarCostoDet(txtOpNbr.Text)
        dgvDetCost.Rows.Clear()
        For Each l In lsCostos
            Dim row As String() = New String() {l.Costid, l.Descr, l.Total_cost.ToString("f2"), l.Grupo, l.Prioridad, l.Tipo}
            dgvDetCost.Rows.Add(row)
            If l.Tipo = "C" Or l.Tipo = "F" Then
                dgvDetCost.Rows(dgvDetCost.Rows.Count - 1).ReadOnly = True
                If l.Tipo = "C" Then
                    dgvDetCost.Rows(dgvDetCost.Rows.Count - 1).DefaultCellStyle.BackColor = Color.Blue
                    dgvDetCost.Rows(dgvDetCost.Rows.Count - 1).DefaultCellStyle.ForeColor = Color.White
                    dgvDetCost.Rows(dgvDetCost.Rows.Count - 1).DefaultCellStyle.Font = New System.Drawing.Font(dgvDetCost.DefaultCellStyle.Font, System.Drawing.FontStyle.Bold)
                End If
            End If

        Next
        dgvDetCost.Refresh()

    End Sub
    Private Sub cargarDetalles(ByVal lsCostos As List(Of xm_cost_item))
        dgvDetCost.Rows.Clear()
        For Each l In lsCostos
            Dim row As String() = New String() {l.Costid, l.Descr, l.Total_cost, l.Grupo, l.Prioridad}
            dgvDetCost.Rows.Add(row)
            If l.Tipo = "C" Or l.Tipo = "F" Then
                dgvDetCost.Rows(dgvDetCost.Rows.Count - 1).ReadOnly = True
                If l.Tipo = "C" Then
                    dgvDetCost.Rows(dgvDetCost.Rows.Count - 1).DefaultCellStyle.BackColor = Color.Blue
                    dgvDetCost.Rows(dgvDetCost.Rows.Count - 1).DefaultCellStyle.ForeColor = Color.White
                    dgvDetCost.Rows(dgvDetCost.Rows.Count - 1).DefaultCellStyle.Font = New System.Drawing.Font(dgvDetCost.DefaultCellStyle.Font, System.Drawing.FontStyle.Bold)
                End If
            End If
        Next

    End Sub
    Private Sub cargarDetalles(ByVal lsCostos As List(Of xm_cierre_det))
        dgvDetCost.Rows.Clear()
        For Each l In lsCostos
            Dim row As String() = New String() {l.Costid, l.Descr, l.Total_cost, l.Grupo, l.Sequence, l.Tipo}
            dgvDetCost.Rows.Add(row)
            If l.Tipo = "C" Or l.Tipo = "F" Then
                dgvDetCost.Rows(dgvDetCost.Rows.Count - 1).ReadOnly = True
                If l.Tipo = "C" Then
                    dgvDetCost.Rows(dgvDetCost.Rows.Count - 1).DefaultCellStyle.BackColor = Color.Blue
                    dgvDetCost.Rows(dgvDetCost.Rows.Count - 1).DefaultCellStyle.ForeColor = Color.White
                    dgvDetCost.Rows(dgvDetCost.Rows.Count - 1).DefaultCellStyle.Font = New System.Drawing.Font(dgvDetCost.DefaultCellStyle.Font, System.Drawing.FontStyle.Bold)
                End If
            End If

        Next
    End Sub
    Private Sub cargarEstado()
        cmbEstado.Items.Insert(0, "Activo")
        cmbEstado.Items.Insert(1, "Cerrado")
    End Sub
    Private Function cargarParametros()
        Dim objParams As xm_config_per = BLCostos.obtenerParametros

        txtPerpost.Text = objParams.Perpost
        txtHolgSeg.Text = objParams.Holg_seguro.ToString("f2")
        txtTasaSeg.Text = objParams.Tasa_seguro.ToString("f2")
        txtPlazoVenta.Text = objParams.Dias_plazo_vta.ToString()
        txtOverhead.Text = objParams.Overhead.ToString("f2")
        txtMerma.Text = objParams.Tasa_merma.ToString("f2")
        txtCostoFinanc.Text = objParams.Tasa_interes.ToString("f2")
        Return True
    End Function
    Private Sub cargarMotonave()
        For Each obj As segdef In BLCostos.obtenerMotonaves
            cmbMotonave.Items.Add(obj)
        Next
    End Sub

    Private Sub cargarOrigen()
        Dim MySource As New AutoCompleteStringCollection()

        MySource.AddRange(BLCostos.obtenerOrigenes.ToArray)
        txtOrigen.AutoCompleteCustomSource.Clear()
        txtOrigen.AutoCompleteCustomSource = MySource
    End Sub
    Private Sub cargarPerpost()
        Dim MySource As New AutoCompleteStringCollection()

        MySource.AddRange(BLCostos.obtenerPerpost.ToArray)
        txtPerpost.AutoCompleteCustomSource.Clear()
        txtPerpost.AutoCompleteCustomSource = MySource
    End Sub
    Private Sub cargarPresentaciones()
        cmbTipoPresent.Items.Clear()
        For Each obj As segdef In BLCostos.obtenerPresentaciones
            cmbTipoPresent.Items.Add(obj)
        Next
    End Sub
    Private Sub cargarProductos()
        Dim MySource As New AutoCompleteStringCollection()

        MySource.AddRange(BLCostos.obtenerTipoProductos.ToArray)
        txtProducto.AutoCompleteCustomSource.Clear()
        txtProducto.AutoCompleteCustomSource = MySource
    End Sub
    Private Sub cargarPuertos()
        Dim MySource As New AutoCompleteStringCollection()

        MySource.AddRange(BLCostos.obtenerPuertos.ToArray)
        txtPuerto.AutoCompleteCustomSource.Clear()
        txtPuerto.AutoCompleteCustomSource = MySource
    End Sub

    Private Sub cargarTipoDespacho()
        For Each d In BLCostos.obtenerTipoDespacho()
            cmbTipoDespacho.Items.Add(d)
        Next
        
    End Sub
    Private Sub cargarTipoVenta()
        cmbTipoVenta.Items.Insert(0, "Almacen")
        cmbTipoVenta.Items.Insert(1, "Vapor Camion")

    End Sub
    Private Sub cargarUMs()
        Dim MySource As New AutoCompleteStringCollection()

        MySource.AddRange(BLCostos.obtenerUms.ToArray)
        txtUM.AutoCompleteCustomSource.Clear()
        txtUM.AutoCompleteCustomSource = MySource
    End Sub
    Private Sub cargarVentana()
        cargarCabecera()
        cargarDetalles()
        If cmbEstado.SelectedIndex = 0 Then
            habilitarVentana()
            habilitarFletes()
            habilitarCostosPresentacion()
        End If
        cmbEstado.Visible = True
        lbEstado.Visible = True
    End Sub
    Private Sub deshabilitarVentana()
        limpiarNotificaciones()

        txtOpNbr.Enabled = True
        txtCliente.Enabled = False
        txtProducto.Enabled = False
        dtpFecha.Enabled = False
        txtOrigen.Enabled = False
        txtPuerto.Enabled = False
        cmbMotonave.Enabled = False
        txtQtyCierre.Enabled = False
        txtUM.Enabled = False
        txtPrecVenta.Enabled = False
        cmbCbotFut.Enabled = False
        cmbCbotPrim.Enabled = False
        cmbTipoDespacho.Enabled = False
        cmbTipoVenta.Enabled = False
        cmbTipoPresent.Enabled = False
        'txtSpread.Enabled = False
        txtFutCompra.Enabled = False
        'txtPerpost.Enabled = False
        'txtHolgSeg.Enabled = False
        'txtTasaSeg.Enabled = False
        txtPlazoVenta.Enabled = False

        tsbtnGuardar.Enabled = False


        dgvDetCost.ReadOnly = True
    End Sub
    Private Function guardarCostos() As String
        Dim strOprNbr As String
        Me.Cursor = Cursors.WaitCursor
        strOprNbr = BLCostos.guardarCostos(strCustid, txtProducto.Text, dtpFecha.Value.Date.ToString("s"), _
                                      strOrigen, strPuerto, txtCostoFinanc.Text, TryCast(cmbMotonave.SelectedItem, segdef).Id, _
                                      txtQtyCierre.Text, txtUM.Text, txtPrecVenta.Text, _
                                      TryCast(cmbCbotPrim.SelectedItem, xm_cbot_mes).Id_cbot, _
                                      TryCast(cmbCbotPrim.SelectedItem, xm_cbot_mes).Id_cbot, txtPerpost.Text, txtHolgSeg.Text, _
                                      txtTasaSeg.Text, txtPlazoVenta.Text, txtOverhead.Text, txtCantidadContratos.Text, _
                                      txtSpread.Text, txtMerma.Text, cmbTipoVenta.SelectedItem.ToString, _
                                      CType(cmbTipoDespacho.SelectedItem, tipodespacho).ShipViaId, txtFutCompra.Text, _
                                      IIf(cmbEstado.SelectedIndex = 0, "A", "C"), CType(cmbTipoPresent.SelectedItem, segdef).Id, _
                                      obtenerDetallesCostos())
        Me.Cursor = Cursors.Arrow
        Return strOprNbr
    End Function
    Private Sub habilitarCostoById(ByVal costid As String)
        For Each r As DataGridViewRow In dgvDetCost.Rows
            If r.Cells(0).Value.trim = costid And r.Cells(5).Value.trim = "V" Then
                r.ReadOnly = False
                'r.Cells(2).Value = "0.00"
                'Exit For
            End If
        Next
        'actualizarCalculoCostos(BLCostos.calcularMontos(obtenerDetallesCostos, Val(txtHolgSeg.Text), _
        '                                                   Val(txtTasaSeg.Text), Val(txtPlazoVenta.Text), _
        '                                                    Val(txtOverhead.Text), Val(txtMerma.Text), objCbotProd.Fact_UC_USD, txtCostoFinanc.Text))
        'actualizarCalculos()
    End Sub
    Private Sub deshabilitarCostoById(ByVal costid As String)
        For Each r As DataGridViewRow In dgvDetCost.Rows
            If r.Cells(0).Value.trim = costid Then
                r.ReadOnly = True
                r.Cells(2).Value = "0.00"
                'Exit For
            End If
        Next
        'actualizarCalculoCostos(BLCostos.calcularMontos(obtenerDetallesCostos, Val(txtHolgSeg.Text), _
        '                                                   Val(txtTasaSeg.Text), Val(txtPlazoVenta.Text), _
        '                                                   Val(txtOverhead.Text), Val(txtMerma.Text), objCbotProd.Fact_UC_USD, txtCostoFinanc.Text))
        actualizarCalculos()
    End Sub
    Private Sub habilitarCostosPresentacion()
        Select Case CType(cmbTipoPresent.SelectedItem, segdef).Id.Trim
            Case "01" ' Granel
                deshabilitarCostoById("MOL")
                deshabilitarCostoById("ENS")
            Case "02" ' Envasado sin moler
                habilitarCostoById("ENS")
                deshabilitarCostoById("MOL")
            Case "03" ' Molido y ensacado
                habilitarCostoById("ENS")
                habilitarCostoById("MOL")
        End Select
    End Sub
    Private Sub habilitarFletes()
        Select Case cmbTipoVenta.SelectedItem.ToString.Trim
            Case "Almacen"
                Select Case CType(cmbTipoDespacho.SelectedItem, tipodespacho).ShipViaId.Trim
                    Case "CLIENTE RECOGE"
                        habilitarCostoById("FLED")
                        deshabilitarCostoById("FLET")
                    Case "PUESTOENCLIENTE"
                        habilitarCostoById("FLED")
                        habilitarCostoById("FLET")
                End Select
            Case "Vapor Camion"
                Select Case CType(cmbTipoDespacho.SelectedItem, tipodespacho).ShipViaId.Trim
                    Case "CLIENTE RECOGE"
                        deshabilitarCostoById("FLED")
                        deshabilitarCostoById("FLET")
                    Case "PUESTOENCLIENTE"
                        habilitarCostoById("FLED")
                        habilitarCostoById("FLET")
                End Select
        End Select
    End Sub
    Private Sub habilitarVentana()
        txtOpNbr.Enabled = False
        txtCliente.Enabled = True
        txtProducto.Enabled = True
        dtpFecha.Enabled = True
        txtOrigen.Enabled = True
        txtPuerto.Enabled = True

        cmbMotonave.Enabled = True
        txtQtyCierre.Enabled = True
        txtUM.Enabled = True
        txtPrecVenta.Enabled = True
        cmbCbotFut.Enabled = True
        cmbCbotPrim.Enabled = True
        cmbTipoDespacho.Enabled = True
        cmbTipoVenta.Enabled = True
        cmbTipoDespacho.Enabled = True
        cmbTipoPresent.Enabled = True
        'txtSpread.Enabled = True
        txtFutCompra.Enabled = True
        'txtPerpost.Enabled = True
        'txtHolgSeg.Enabled = True
        'txtTasaSeg.Enabled = True
        txtPlazoVenta.Enabled = True

        tsbtnGuardar.Enabled = True
        dgvDetCost.ReadOnly = False
    End Sub
    Private Sub iniciarVentana()
        limpiarCampos()
        cargarParametros()
        cmbEstado.Enabled = False
        dtpFecha.Value = Date.Now
        txtOpNbr.Enabled = False
        txtCantidadContratos.Enabled = False
        txtOverhead.Enabled = False
        txtMerma.Enabled = False
        txtCostoFinanc.Enabled = False
        txtPerpost.Enabled = False
        txtHolgSeg.Enabled = False
        txtTasaSeg.Enabled = False
        txtCompensacion.Enabled = False
        txtSpread.Enabled = False
        txtTotal.Enabled = False
        cmbEstado.Visible = False
        cmbCbotPrim.Enabled = False
        lbEstado.Visible = False
    End Sub
    Private Sub limpiarCampos()
        txtCliente.Clear()
        txtOpNbr.Clear()
        cmbEstado.SelectedIndex = 0
        cmbEstado.Visible = False
        lbEstado.Visible = False
        txtProducto.Clear()
        txtOrigen.Clear()
        txtPuerto.Clear()
        cmbMotonave.SelectedItem = Nothing
        txtCostoFinanc.Clear()
        txtPerpost.Clear()
        dtpFecha.Value = Date.Now
        txtCostoFinanc.Text = "0.00"
        txtQtyCierre.Text = "0.00"
        txtPrecVenta.Text = "0.00"
        cmbCbotFut.Items.Clear()
        cmbCbotPrim.Items.Clear()
        cmbTipoDespacho.SelectedIndex = 0
        cmbTipoVenta.SelectedIndex = 0
        cmbTipoPresent.SelectedIndex = 0
        txtCantidadContratos.Text = "0.00"
        txtSpread.Text = "0.00"
        txtHolgSeg.Text = "0.00"
        txtTasaSeg.Text = "0.00"
        txtPlazoVenta.Text = "0"
        txtOverhead.Text = "0.00"
        txtMerma.Text = "0.00"
        txtFutCompra.Text = "0.00"
        txtCompensacion.Text = "0.00"
        txtTotal.Text = "0.00"
        intCantPuntos = 0
        strCustid = ""
        strOrigen = ""
        strPuerto = ""
    End Sub

    Private Sub tsbtnNuevo_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles tsbtnNuevo.Click
        Dim result1 As DialogResult = MessageBox.Show("¿Desea guardar los cambios?", _
           "Plantilla de Costos", _
           MessageBoxButtons.YesNoCancel)

        Select Case result1
            Case Windows.Forms.DialogResult.Yes
                If validarPantalla() Then
                    If txtOpNbr.Text = "" Then guardarCostos() Else actualizarCostos()
                    limpiarVentana()
                End If
            Case Windows.Forms.DialogResult.No
                limpiarVentana()
        End Select

    End Sub
    Private Sub limpiarVentana()
        limpiarCampos()
        limpiarNotificaciones()
        cargarClientes()
        cargarProductos()
        cargarParametros()
        habilitarVentana()
        llenarGrilla()
    End Sub
    Private Sub llenarCostoEnGrillaByID(ByVal costid As String, ByVal value As Double)
        For Each r As DataGridViewRow In dgvDetCost.Rows
            If r.Cells(0).Value.trim = costid Then
                r.Cells(2).Value = value.ToString("f2")
                Return
            End If
        Next
    End Sub

    Private Sub llenarGrilla()
        Dim lsCostos As List(Of xm_cost_item) = BLCostos.obtenerCostos
        Dim dlOV As Double = 0.0
        dgvDetCost.Rows.Clear()
        For Each l In lsCostos
            Dim row As String() = New String() {l.Costid, l.Descr, "0.00", l.Grupo, l.Prioridad, l.Tipo}
            dgvDetCost.Rows.Add(row)
            If l.Tipo = "C" Or l.Tipo = "F" Then
                dgvDetCost.Rows(dgvDetCost.Rows.Count - 1).ReadOnly = True
                If l.Tipo = "C" Then
                    dgvDetCost.Rows(dgvDetCost.Rows.Count - 1).DefaultCellStyle.BackColor = Color.Blue
                    dgvDetCost.Rows(dgvDetCost.Rows.Count - 1).DefaultCellStyle.ForeColor = Color.White
                    dgvDetCost.Rows(dgvDetCost.Rows.Count - 1).DefaultCellStyle.Font = New System.Drawing.Font(dgvDetCost.DefaultCellStyle.Font, System.Drawing.FontStyle.Bold)
                End If
            End If
        Next
        llenarCostoEnGrillaByID("OVH", txtOverhead.Text)

    End Sub
    Private Sub limpiarNotificaciones()
        ErrorProvider1.SetError(txtCliente, "")
        ErrorProvider1.SetError(txtProducto, "")
        ErrorProvider1.SetError(txtOrigen, "")
        ErrorProvider1.SetError(txtPuerto, "")
        ErrorProvider1.SetError(cmbCbotFut, "")
        ErrorProvider1.SetError(cmbCbotPrim, "")
        ErrorProvider1.SetError(cmbMotonave, "")
        ErrorProvider1.SetError(txtFutCompra, "")
        ErrorProvider1.SetError(txtPrecVenta, "")
    End Sub

    Private Sub notificarValidacionCampo(ByVal Campo As TextBox, ByVal valor As String, ByVal mensaje As String)
        If valor = "" And Campo.Text <> "" Then
            MessageBox.Show(mensaje, Me.Text, MessageBoxButtons.OK, MessageBoxIcon.Information)
            ErrorProvider1.SetError(Campo, mensaje)

        Else
            ErrorProvider1.SetError(Campo, "")
        End If
    End Sub

    Private Sub notificarValidacionCampoGuardado(ByVal Campo As TextBox, ByVal valor As String, ByVal mensaje As String)
        If valor = "" Or valor = "0.00" Or valor = "0" Then
            If intCantNot = 0 Then MessageBox.Show("No se pudo completar la transacción, por favor ingresar todos los campos exigibles.", Me.Text, MessageBoxButtons.OK, MessageBoxIcon.Warning)
            ErrorProvider1.SetError(Campo, mensaje)
            intCantNot += 1
        Else
            ErrorProvider1.SetError(Campo, "")
        End If
    End Sub

    Private Sub notificarValidacionComboGuardado(ByVal cmb As ComboBox, ByVal msj As String)
        If cmb.SelectedItem Is Nothing Then
            If intCantNot = 0 Then MessageBox.Show("No se pudo completar la transacción, por favor ingresar todos los campos exigibles.", Me.Text, MessageBoxButtons.OK, MessageBoxIcon.Warning)
            ErrorProvider1.SetError(cmb, msj)
            intCantNot += 1
        Else
            ErrorProvider1.SetError(cmb, "")
        End If
    End Sub
    Private Sub notificarValidaciones()
        intCantNot = 0
        notificarValidacionCampoGuardado(txtCliente, strCustid, "Ingrese un " + txtCliente.Name.Substring(3, txtCliente.Name.Length - 3) + " valido")
        notificarValidacionCampoGuardado(txtProducto, txtProducto.Text, "Ingrese un " + txtProducto.Name.Substring(3, txtProducto.Name.Length - 3) + " valido")
        notificarValidacionCampoGuardado(txtOrigen, strOrigen, "Ingrese un " + txtOrigen.Name.Substring(3, txtOrigen.Name.Length - 3) + " valido")
        notificarValidacionCampoGuardado(txtPuerto, strPuerto, "Ingrese un " + txtPuerto.Name.Substring(3, txtPuerto.Name.Length - 3) + " valido")
        notificarValidacionCampoGuardado(txtPrecVenta, txtPrecVenta.Text, "Ingrese un valor para el precio de venta.")
        notificarValidacionCampoGuardado(txtPlazoVenta, txtPlazoVenta.Text, "Ingrese un plazo de venta mayor a 0.")
        'notificarValidacionCampoGuardado(txtFutCompra, txtFutCompra.Text, "Ingrese un valor para el futuro de compra.")
        notificarValidacionComboGuardado(cmbMotonave, "Seleccione una motonave para el costeo.")
        notificarValidacionComboGuardado(cmbCbotFut, "Seleccione un mes para la compra de los futuros.")
        'notificarValidacionComboGuardado(cmbCbotPrim, "Seleccione un mes para la compra de las primas.")
        intCantNot = 0
    End Sub
    Private Function obtenerCostoEnGrillaById(ByVal costid As String) As Double
        For Each r As DataGridViewRow In dgvDetCost.Rows
            If r.Cells(0).Value.trim = costid Then
                Return r.Cells(2).Value
            End If
        Next
        Return 0
    End Function

    Private Function obtenerDetallesCostos() As List(Of xm_cierre_det)
        Dim lsCostos As List(Of xm_cierre_det) = New List(Of xm_cierre_det)
        For Each r As DataGridViewRow In dgvDetCost.Rows
            Dim a As xm_cierre_det = New xm_cierre_det()
            a.Costid = r.Cells(0).Value()
            a.Descr = r.Cells(1).Value()
            a.Total_cost = r.Cells(2).Value()
            a.Grupo = r.Cells(3).Value
            a.Sequence = r.Cells(4).Value()
            a.Tipo = r.Cells(5).Value()
            lsCostos.Add(a)
        Next
        Return lsCostos
    End Function

    Private Function obtenerIndiceCbot(ByVal cmb As ComboBox, ByVal cbotmesid As String) As Integer
        Dim aux As Integer = 0
        For Each c In cmb.Items
            If TryCast(c, xm_cbot_mes).Id_cbot = cbotmesid Then Return aux
            aux += 1
        Next
        Return 0
    End Function
    Private Function obtenerIndiceDespacho(ByVal cmb As ComboBox, ByVal tipdespacho As String) As Integer
        Dim aux As Integer = 0
        For Each c In cmb.Items
            If TryCast(c, tipodespacho).ShipViaId = tipdespacho Then Return aux
            aux += 1
        Next
        Return 0
    End Function

    Private Function obtenerIndiceNave(ByVal cmb As ComboBox, ByVal segdefid As String) As Integer
        Dim aux As Integer = 0
        For Each c In cmb.Items
            If TryCast(c, segdef).Id.Trim = segdefid Then Return aux
            aux += 1
        Next
        Return 0
    End Function
    Private Function validarPantalla() As Boolean
        txtOpNbr.Select()
        If (strCustid = "" Or txtProducto.Text = "" Or strOrigen = "" Or strPuerto = "" Or _
            cmbCbotFut.SelectedItem Is Nothing Or cmbCbotPrim.SelectedItem Is Nothing _
            Or cmbMotonave.SelectedItem Is Nothing Or txtPrecVenta.Text = "0.00" _
            Or txtPlazoVenta.Text = "0") Then
            notificarValidaciones()
            Return False
        End If
        limpiarNotificaciones()
        Return True
    End Function

    Private Sub frmRegistarCostos_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load

        'Dim parms() As String = System.Environment.GetCommandLineArgs()

        'For Each s In parms
        '    MsgBox(s)
        'Next

        ErrorProvider1 = New ErrorProvider()
        objCbotProd = New xm_cbot_prod
        bModoBusqueda = False
        cargarCierres()
        cargarClientes()
        cargarProductos()
        cargarOrigen()
        cargarPuertos()
        cargarUMs()
        cargarMotonave()
        cargarTipoDespacho()
        cargarTipoVenta()
        cargarEstado()
        cargarPresentaciones()
        iniciarVentana()
        llenarGrilla()
        habilitarFletes()
        habilitarCostosPresentacion()


    End Sub

    Private Sub ToolStripButton1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles tsbtnGuardar.Click
        If validarPantalla() Then
            If txtOpNbr.Text = "" Then
                txtOpNbr.Text = guardarCostos()
                cmbEstado.Visible = True
                lbEstado.Visible = True
            Else
                actualizarCostos()
            End If
        End If
    End Sub

    Private Sub txtCliente_Leave(ByVal sender As Object, ByVal e As System.EventArgs) Handles txtCliente.Leave
        strCustid = BLCostos.validarCliente(txtCliente.Text)
        If strCustid = "" And txtCliente.Text <> "" Then
            notificarValidacionCampo(txtCliente, strCustid, "Ingrese un " + txtCliente.Name.Substring(3, txtCliente.Name.Length - 3) + " valido")
            txtCliente.Select()
            txtCliente.SelectAll()
        Else
            If cmbEstado.SelectedIndex = 0 Then
                notificarValidacionCampo(txtCliente, strCustid, "Ingrese un " + txtCliente.Name.Substring(3, txtCliente.Name.Length - 3) + " valido")
                actualizarCalculoCostos(BLCostos.calcularMontos(obtenerDetallesCostos, Val(txtHolgSeg.Text), _
                                                                Val(txtTasaSeg.Text), Val(txtPlazoVenta.Text), _
                                                                Val(txtOverhead.Text), Val(txtMerma.Text), objCbotProd.Fact_UC_USD, txtCostoFinanc.Text, txtProducto.Text, strOrigen, strPuerto, txtPerpost.Text))
                habilitarFletes()
                habilitarCostosPresentacion()
            End If
        End If

    End Sub

    Private Sub txtOrigen_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles txtOrigen.KeyPress
        If e.KeyChar = Chr(13) Then 'Chr(13) is the Enter Key
            cargarVentana()
        End If
    End Sub
    Private Sub txtOrigen_Leave(ByVal sender As Object, ByVal e As System.EventArgs) Handles txtOrigen.Leave
        strOrigen = BLCostos.validarOrigen(txtOrigen.Text)
        If strOrigen = "" And txtOrigen.Text <> "" Then
            txtOrigen.Select()
            txtOrigen.SelectAll()
        Else
            If cmbEstado.SelectedIndex = 0 Then
                notificarValidacionCampo(txtOrigen, strOrigen, "Ingrese un " + txtOrigen.Name.Substring(3, txtOrigen.Name.Length - 3) + " valido")
                actualizarCalculoCostos(BLCostos.calcularMontos(obtenerDetallesCostos, Val(txtHolgSeg.Text), _
                                                                Val(txtTasaSeg.Text), Val(txtPlazoVenta.Text), _
                                                                Val(txtOverhead.Text), Val(txtMerma.Text), objCbotProd.Fact_UC_USD, txtCostoFinanc.Text, txtProducto.Text, strOrigen, strPuerto, txtPerpost.Text))
                habilitarFletes()
                habilitarCostosPresentacion()
            End If

        End If

    End Sub
    Private Sub txtPuerto_Leave(ByVal sender As Object, ByVal e As System.EventArgs) Handles txtPuerto.Leave
        strPuerto = BLCostos.validarPuerto(txtPuerto.Text)
        Dim aux As TextBox = sender
        If strPuerto = "" And txtPuerto.Text <> "" Then
            notificarValidacionCampo(txtPuerto, strPuerto, "Ingrese un " + txtPuerto.Name.Substring(3, txtPuerto.Name.Length - 3) + " valido")
            'MsgBox(aux.AutoCompleteCustomSource.Contains(aux.Text).ToString)
            txtPuerto.Select()
            txtPuerto.SelectAll()
        Else
            If cmbEstado.SelectedIndex = 0 Then
                notificarValidacionCampo(txtPuerto, strPuerto, "Ingrese un " + txtPuerto.Name.Substring(3, txtPuerto.Name.Length - 3) + " valido")
                actualizarCalculoCostos(BLCostos.calcularMontos(obtenerDetallesCostos, Val(txtHolgSeg.Text), _
                                                                Val(txtTasaSeg.Text), Val(txtPlazoVenta.Text), _
                                                                Val(txtOverhead.Text), Val(txtMerma.Text), objCbotProd.Fact_UC_USD, txtCostoFinanc.Text, txtProducto.Text, strOrigen, strPuerto, txtPerpost.Text))
                habilitarFletes()
                habilitarCostosPresentacion()
            End If

        End If

    End Sub

    Private Sub dgvDetCost_CellValidating(ByVal sender As System.Object, ByVal e As System.Windows.Forms.DataGridViewCellValidatingEventArgs) Handles dgvDetCost.CellValidating
        If e.ColumnIndex = 2 Then
            If Not IsNumeric(e.FormattedValue) Then
                e.Cancel = True
            End If
        End If

    End Sub

    Private Sub tsbtnBuscar_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles tsbtnBuscar.Click
        bModoBusqueda = True
        limpiarVentana()
        cargarCierres()
        deshabilitarVentana()
    End Sub
    Private Sub txtOpNbr_KeyUp(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles txtOpNbr.KeyUp
        If e.KeyCode = Keys.Enter Then
            Me.Cursor = Cursors.WaitCursor
            cargarVentana()
            Me.Cursor = Cursors.Arrow
            bModoBusqueda = False
        End If
    End Sub
    Private Sub dgvDetCost_RowEnter(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles dgvDetCost.RowEnter
        If txtCliente.Enabled = True Then
            If e.ColumnIndex = 2 Then
                If cmbEstado.SelectedIndex = 0 Then
                    actualizarCalculoCostos(BLCostos.calcularMontos(obtenerDetallesCostos, Val(txtHolgSeg.Text), _
                                                                Val(txtTasaSeg.Text), Val(txtPlazoVenta.Text), _
                                                                Val(txtOverhead.Text), Val(txtMerma.Text), objCbotProd.Fact_UC_USD, txtCostoFinanc.Text, txtProducto.Text, strOrigen, strPuerto, txtPerpost.Text))
                    actualizarCalculos()
                    habilitarFletes()
                    habilitarCostosPresentacion()
                    'llenarCostoEnGrillaByID("OVH", txtOverhead.Text)
                End If
                
            End If
        End If
    End Sub
    Private Sub txtTasaInteres_Leave(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles txtCostoFinanc.Leave, txtQtyCierre.Leave, txtPrecVenta.Leave, txtMerma.Leave, txtOverhead.Leave, txtTasaSeg.Leave, txtHolgSeg.Leave, txtSpread.Leave, txtCantidadContratos.Leave, txtCompensacion.Leave, txtFutCompra.Leave, txtTotal.Leave
        If txtCliente.Enabled = True Then
            If sender.text <> "" Then
                If Not IsNumeric(sender.Text) Then
                    sender.text = "0.00"
                    sender.Select()
                    sender.SelectAll()
                Else
                    Dim aux As Double = sender.text
                    sender.text = aux.ToString("f2")
                    If cmbEstado.SelectedIndex = 0 Then
                        actualizarCalculoCostos(BLCostos.calcularMontos(obtenerDetallesCostos, Val(txtHolgSeg.Text), _
                                                                 Val(txtTasaSeg.Text), Val(txtPlazoVenta.Text), _
                                                                 Val(txtOverhead.Text), Val(txtMerma.Text), objCbotProd.Fact_UC_USD, txtCostoFinanc.Text, txtProducto.Text, strOrigen, strPuerto, txtPerpost.Text))
                        actualizarCalculos()
                        habilitarFletes()
                        habilitarCostosPresentacion()
                    End If
                End If
            Else
                sender.text = "0.00"
            End If
        End If
    End Sub

    Private Sub txtPlazoVenta_Leave(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles txtPlazoVenta.Leave
        If txtCliente.Enabled = True Then
            If sender.text <> "" Then
                If Not IsNumeric(sender.Text) Then
                    sender.text = "0"
                    sender.Select()
                    sender.SelectAll()
                Else
                    Dim aux As Integer = sender.text
                    sender.text = aux.ToString()
                    If cmbEstado.SelectedIndex = 0 Then
                        actualizarCalculoCostos(BLCostos.calcularMontos(obtenerDetallesCostos, Val(txtHolgSeg.Text), _
                                                                Val(txtTasaSeg.Text), Val(txtPlazoVenta.Text), _
                                                                Val(txtOverhead.Text), Val(txtMerma.Text), objCbotProd.Fact_UC_USD, txtCostoFinanc.Text, txtProducto.Text, strOrigen, strPuerto, txtPerpost.Text))
                        actualizarCalculos()
                        habilitarFletes()
                        habilitarCostosPresentacion()
                    End If

                End If
            Else
                sender.text = "0"
            End If
        End If

    End Sub
    Private Sub txtProducto_Leave(ByVal sender As Object, ByVal e As System.EventArgs) Handles txtProducto.Leave
        'MsgBox("Producto Original: " + strProducto)
        'MsgBox("Producto Cambiado: " + txtProducto.Text)
        If txtCliente.Enabled = True Then
            If cmbEstado.SelectedIndex = 0 Then
                objCbotProd = BLCostos.obtenerCbotProducto(txtProducto.Text)
                actualizarCalculoCostos(BLCostos.calcularMontos(obtenerDetallesCostos, Val(txtHolgSeg.Text), _
                                                                Val(txtTasaSeg.Text), Val(txtPlazoVenta.Text), _
                                                                Val(txtOverhead.Text), Val(txtMerma.Text), objCbotProd.Fact_UC_USD, txtCostoFinanc.Text, txtProducto.Text, strOrigen, strPuerto, txtPerpost.Text))
                habilitarFletes()
                habilitarCostosPresentacion()
                If String.Compare(strProducto, txtProducto.Text) Then
                    actualizarCalculos()
                    actualizarCBOT()
                    actualizarUm()
                End If
            End If
        End If
    End Sub
    Private Sub cmbTipoDespacho_SelectionChangeCommitted(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmbTipoVenta.SelectionChangeCommitted, cmbTipoDespacho.SelectionChangeCommitted
        If cmbEstado.SelectedIndex = 0 Then
            actualizarCalculoCostos(BLCostos.calcularMontos(obtenerDetallesCostos, Val(txtHolgSeg.Text), _
                                                                    Val(txtTasaSeg.Text), Val(txtPlazoVenta.Text), _
                                                                    Val(txtOverhead.Text), Val(txtMerma.Text), objCbotProd.Fact_UC_USD, txtCostoFinanc.Text, txtProducto.Text, strOrigen, strPuerto, txtPerpost.Text))
            habilitarFletes()
            habilitarCostosPresentacion()
        End If
        
    End Sub
    Private Sub txtCliente_MouseDown(ByVal sender As System.Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles txtUM.MouseDown, txtQtyCierre.MouseDown, txtPuerto.MouseDown, txtProducto.MouseDown, txtOrigen.MouseDown, txtCliente.MouseDown, cmbMotonave.MouseDown
        sender.selectall()
    End Sub

    Private Sub frmRegistarCostos_Shown(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Shown
        If String.IsNullOrEmpty(txtPerpost.Text) Then
            MessageBox.Show("No se encuentran registrados los parametros para el periodo actual.", Me.Text, MessageBoxButtons.OK, MessageBoxIcon.Information)
            Me.Close()
        End If
    End Sub

    Private Sub txtProducto_Enter(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles txtProducto.Enter
        strProducto = txtProducto.Text
    End Sub

    Private Sub tsbtnCerrarCostos_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles tsbtnCerrarCostos.Click
        Dim result1 As DialogResult = MessageBox.Show("¿Desea cerrar el costeo actual?", _
          "Plantilla de Costos", _
          MessageBoxButtons.YesNoCancel)

        Select Case result1
            Case Windows.Forms.DialogResult.Yes
                cmbEstado.SelectedIndex = 1
                If validarPantalla() Then
                    If txtOpNbr.Text = "" Then guardarCostos() Else actualizarCostos()
                    deshabilitarVentana()
                End If
            Case Windows.Forms.DialogResult.No
                'limpiarVentana()
        End Select
    End Sub

    Private Sub cmbCbotFut_SelectionChangeCommitted(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmbCbotFut.SelectionChangeCommitted
        cmbCbotPrim.SelectedIndex = cmbCbotFut.SelectedIndex
    End Sub

    Private Sub dgvDetCost_Enter(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles dgvDetCost.Enter
        If txtPlazoVenta.Text = "0" And Not bModoBusqueda Then
            MessageBox.Show("El plazo de venta se encuentra en 0 dias, por favor ingrese un valor mayor a 0.", Me.Text, MessageBoxButtons.OK, MessageBoxIcon.Warning)
            txtPlazoVenta.Select()
        End If
    End Sub

    Private Sub cmbTipoPresent_SelectionChangeCommitted(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmbTipoPresent.SelectionChangeCommitted
        If cmbEstado.SelectedIndex = 0 Then
            actualizarCalculoCostos(BLCostos.calcularMontos(obtenerDetallesCostos, Val(txtHolgSeg.Text), _
                                                                    Val(txtTasaSeg.Text), Val(txtPlazoVenta.Text), _
                                                                    Val(txtOverhead.Text), Val(txtMerma.Text), objCbotProd.Fact_UC_USD, txtCostoFinanc.Text, txtProducto.Text, strOrigen, strPuerto, txtPerpost.Text))
            habilitarFletes()
            habilitarCostosPresentacion()
        End If
    End Sub

End Class
